import {
    BASE_URL
} from '../../../http/config';

Page({
    data: {
        answerList: [],
        userInfo: {}, // 当前登录用户
        pageSize: 10 // 每页条数，按你的接口分页大小设置
    },

    onLoad() {
        const user = wx.getStorageSync('userInfo');
        if (user && user.id) {
            this.setData({
                userInfo: user
            }, () => {
                this.getAllAnswers(1, []);
            });
        } else {
            wx.showToast({
                title: '请先登录',
                icon: 'none'
            });
        }
    },

    /**
     * 递归方式分页获取所有回答
     * @param {number} pageNum 当前页码
     * @param {Array} allData 当前已获取的数据
     */
    getAllAnswers(pageNum, allData) {
        const {
            pageSize,
            userInfo
        } = this.data;

        wx.request({
            url: `${BASE_URL}/question/selectDuo?pageNum=${pageNum}&pageSize=${pageSize}`,
            method: 'GET',
            success: (res) => {
                if (res.data.code === 200) {
                    const list = res.data.data.list || [];
                    const userId = userInfo.id;

                    // 过滤当前页中属于当前用户的记录
                    const userAnswers = list.filter(item => item.userId === userId);
                    const newData = allData.concat(userAnswers);

                    if (list.length === pageSize) {
                        // 还有下一页，继续请求
                        this.getAllAnswers(pageNum + 1, newData);
                    } else {
                        // 所有数据请求完毕
                        this.setData({
                            answerList: newData
                        });
                    }
                } else {
                    wx.showToast({
                        title: '加载失败',
                        icon: 'none'
                    });
                }
            },
            fail: () => {
                wx.showToast({
                    title: '请求错误',
                    icon: 'none'
                });
            }
        });
    }
});
